  async function waitForElement(selector, maxWaitTime = 1000, waitTime = 100) {
      // 转换最大等待时间为毫秒
      maxWaitTime = maxWaitTime * 1000;
      // 设置初始等待时间
      let currentWaitTime = 0;

      return new Promise((resolve, reject) => {
          const intervalId = setInterval(() => {
              const element = document.querySelector(selector);
              if (element) {
                  // 元素存在，清除间隔调用并解析Promise
                  clearInterval(intervalId);
                  resolve(element);
              } else if (currentWaitTime >= maxWaitTime) {
                  // 超出最大等待时间，清除间隔调用并拒绝Promise
                  clearInterval(intervalId);
              }
              // 累加当前等待时间
              currentWaitTime += 100;
          }, waitTime);
      });
  }

  function sleep(delay) {
      return new Promise((resolve) => {
          setTimeout(resolve, delay);
      })
  }

  function closeDebugger() {
      // 破解无限Debugger
      var constructorHook = constructor;
      Function.prototype.constructor = function (s) {

          if (s == "debugger") {
              return function () {}
          }
          return constructorHook(s);
      }
      const setInterval = window.setInterval;
      window.setInterval = function (fun, time) {
          console.log(time, 'ddddd', fun.toString());
          if (fun && fun.toString) {
              var funString = fun.toString();
              if (funString.indexOf('debugger') > -1) return;
              if (funString.indexOf('window.close') > -1) return;
          }
          return setInterval(fun, time);
      }
  }

  function slide(selector, offsetX) {
      var slider = document.querySelector(selector);
      var rect = slider.getBoundingClientRect(),
          x0 = rect.x || rect.left,
          y0 = rect.y || rect.top,
          x1 = x0 + offsetX,
          y1 = y0;
      var mousedown = document.createEvent('MouseEvents');
      mousedown.initMouseEvent('mousedown', true, true, window, 0, x0, y0, x0, y0, false, false, false, false, 0, null);
      slider.dispatchEvent(mousedown);

      var mousemove = document.createEvent('MouseEvents');
      mousemove.initMouseEvent('mousemove', true, true, window, 0, x1, y1, x1, y1, false, false, false, false, 0, null);
      slider.dispatchEvent(mousemove);

      var mouseout = document.createEvent('MouseEvents');
      mouseout.initMouseEvent('mouseout', true, true, window, 0, x1, y1, x1, y1, false, false, false, false, 0, null);
      slider.dispatchEvent(mouseout);
  }

  const NotificationManager = {
      notifications: [], // 存储所有通知
      notificationSpacing: 10, // 每条消息之间的间隔


      // 创建美化的通知，支持传递事件处理函数和状态
      showStyledNotification(title, text, status) {
          const notification = document.createElement('div');

          // 根据状态设置背景颜色
          let backgroundColor;
          if (status === 'success') {
              backgroundColor = '#4CAF50'; // 绿色背景
          } else if (status === 'fail') {
              backgroundColor = '#F44336'; // 红色背景
          } else {
              backgroundColor = '#2196F3'; // 默认蓝色背景
          }

          notification.style.position = 'fixed';
          notification.style.top = `${20 + this.notifications.length * (70 + this.notificationSpacing)}px`; // 根据当前通知数量和间隔调整位置
          notification.style.right = '20px';
          notification.style.backgroundColor = backgroundColor; // 设置背景颜色
          notification.style.color = 'white'; // 白色文字
          notification.style.padding = '15px';
          notification.style.borderRadius = '5px';
          notification.style.boxShadow = '0 2px 10px rgba(0,0,0,0.5)';
          notification.style.zIndex = '9999';
          notification.innerHTML = `<strong>${title}</strong><br>${text}`;

          document.body.appendChild(notification);
          this.notifications.push(notification); // 将通知添加到数组中

          // 自动消失
          setTimeout(() => {
              notification.style.opacity = '0';
              setTimeout(() => {
                  document.body.removeChild(notification);
                  this.notifications.shift(); // 从数组中移除已消失的通知
                  this.updateNotificationPositions(); // 更新剩余通知的位置
              }, 20);
          }, 3000);
      },

      // 更新剩余通知的位置
      updateNotificationPositions() {
          this.notifications.forEach((notification, index) => {
              notification.style.top = `${20 + index * (70 + this.notificationSpacing)}px`; // 根据当前通知数量和间隔调整位置
          });
      },

      // 直接调用成功和失败的通知
      success(text) {
          this.showStyledNotification('成功', text, 'success');
      },
      // 直接调用成功和失败的通知
      success(title, text) {
          this.showStyledNotification(title, text, 'success');
      },
      // 直接调用成功和失败的通知
      fail(text) {
          this.showStyledNotification('错误', text, 'fail');
      },
      fail(title, text) {
          this.showStyledNotification(title, text, 'fail');
      }
  };;
  (function () {

      if (typeof GM == 'undefined') {
          this.GM = {};
      }


      if (typeof GM_addStyle == 'undefined') {
          this.GM_addStyle = (aCss) => {
              'use strict';
              let head = document.getElementsByTagName('head')[0];
              if (head) {
                  let style = document.createElement('style');
                  style.setAttribute('type', 'text/css');
                  style.textContent = aCss;
                  head.appendChild(style);
                  return style;
              }
              return null;
          };
      }


      if (typeof GM_registerMenuCommand == 'undefined') {
          this.GM_registerMenuCommand = (caption, commandFunc, accessKey) => {
              if (!document.body) {
                  if (document.readyState === 'loading' &&
                      document.documentElement && document.documentElement.localName === 'html') {
                      new MutationObserver((mutations, observer) => {
                          if (document.body) {
                              observer.disconnect();
                              GM_registerMenuCommand(caption, commandFunc, accessKey);
                          }
                      }).observe(document.documentElement, {
                          childList: true
                      });
                  } else {
                      console.error('GM_registerMenuCommand got no body.');
                  }
                  return;
              }
              let contextMenu = document.body.getAttribute('contextmenu');
              let menu = (contextMenu ? document.querySelector('menu#' + contextMenu) : null);
              if (!menu) {
                  menu = document.createElement('menu');
                  menu.setAttribute('id', 'gm-registered-menu');
                  menu.setAttribute('type', 'context');
                  document.body.appendChild(menu);
                  document.body.setAttribute('contextmenu', 'gm-registered-menu');
              }
              let menuItem = document.createElement('menuitem');
              menuItem.textContent = caption;
              menuItem.addEventListener('click', commandFunc, true);
              menu.appendChild(menuItem);
          };
      }


      if (typeof GM_getResourceText == 'undefined') {
          this.GM_getResourceText = (aRes) => {
              'use strict';
              return GM.getResourceUrl(aRes)
                  .then(url => fetch(url))
                  .then(resp => resp.text())
                  .catch(function (error) {
                      GM.log('Request failed', error);
                      return null;
                  });
          };
      }

      Object.entries({
          'GM_addStyle': 'addStyle',
          'GM_deleteValue': 'deleteValue',
          'GM_getResourceURL': 'getResourceUrl',
          'GM_getValue': 'getValue',
          'GM_listValues': 'listValues',
          'GM_notification': 'notification',
          'GM_openInTab': 'openInTab',
          'GM_registerMenuCommand': 'registerMenuCommand',
          'GM_setClipboard': 'setClipboard',
          'GM_setValue': 'setValue',
          'GM_xmlhttpRequest': 'xmlHttpRequest',
          'GM_getResourceText': 'getResourceText',
      }).forEach(([oldKey, newKey]) => {
          let old = this[oldKey];
          if (old && (typeof GM[newKey] == 'undefined')) {
              GM[newKey] = function (...args) {
                  return new Promise((resolve, reject) => {
                      try {
                          resolve(old.apply(this, args));
                      } catch (e) {
                          reject(e);
                      }
                  });
              };
          }
      });

  }.call(window));


  window.GM_Data = {
      menu_ALL: [],
      menu_ID: [],
      // 注册脚本菜单
      init() {
          for (let i = 0; i < this.menu_ALL.length; i++) { // 如果读取到的值为 null 就写入默认值
              if (GM_getValue(this.menu_ALL[i][0]) == null) {
                  GM_setValue(this.menu_ALL[i][0], this.menu_ALL[i][3])
              };
          }
          this.registerMenuCommand();
      },
      registerMenuCommand() {
          if (this.menu_ID.length != []) {
              for (let i = 0; i < this.menu_ID.length; i++) {
                  GM_unregisterMenuCommand(this.menu_ID[i]);
              }
          }
          for (let i = 0; i < this.menu_ALL.length; i++) { // 循环注册脚本菜单
              this.menu_ALL[i][3] = GM_getValue(this.menu_ALL[i][0]);
              this.menu_ID[i] = GM_registerMenuCommand(`${this.menu_ALL[i][3] ? '✅' : '❌'} ${this.menu_ALL[i][1]}`,
                  function (info) {
                      window.GM_Data.menu_switch(`${window.GM_Data.menu_ALL[i][3]}`,
                          `${window.GM_Data.menu_ALL[i][0]}`, `${window.GM_Data.menu_ALL[i][2]}`);
                  }
              );
              if (typeof this.menu_ALL[i][4] === 'function') {
                  this.menu_ALL[i][4].call();
              }
          }

          this.menu_ID[this.menu_ID.length] = GM_registerMenuCommand('💬 反馈 & 建议', function () {
              alert("暂时未添加")
          });
      },
      // 菜单开关
      menu_switch(menu_status, Name, Tips) {
          if (menu_status == 'true') {
              GM_setValue(`${Name}`, false);
              GM_notification({
                  text: `已关闭 [${Tips}] 功能\n（点击刷新网页后生效）`,
                  timeout: 3500,
                  onclick: function () {}
              });
          } else {
              GM_setValue(`${Name}`, true);
              GM_notification({
                  text: `已开启 [${Tips}] 功能\n（点击刷新网页后生效）`,
                  timeout: 3500,
                  onclick: function () {}
              });
          }
          this.registerMenuCommand(); // 重新注册脚本菜单
      }

  };


window.TOOLS = {
      // 操作区
      actionDom(configItem) {
        let actionDom = [];
        for (let i = 0; i < configItem.length; i++) {
          let checkObj = null;
          if (configItem[i].type === "checked") {
            checkObj = this.checkBox(configItem[i]);
          } else if (configItem[i].type === "button") {
            checkObj = this.buttonBox(configItem[i]);
          } else if (configItem[i].type === "radio") {
            checkObj = this.radioBox(configItem[i]);
          } else if (configItem[i].type === "input") {
            checkObj = this.inputBox(configItem[i]);
          }
          actionDom.push(checkObj);
        }
        return actionDom;
      },
      // 设置隐藏显示
      displayDom(domNode, type) {
        if (!domNode) {
          return;
        }
        // 对于一些动态加载的节点 如果没有查到就加入 一个错误队列中 每1000毫秒查找一次
        let dom = this.getElement(domNode);
        let errorList = [];
        if (dom && dom.length > 0) {
          dom.forEach((item) => {
            item.style["display"] = type ? "block" : "none";
          });
        } else {
          errorList.push({
            domNode,
            type,
          });
        }

        if (errorList.length !== 0) {
          let i = 0;
          let interval = setInterval(() => {
            if (i <= 5) {
              errorList.forEach((item) => {
                let errorDom = this.getElement(domNode);
                if (errorDom && errorDom.length > 0) {
                  errorDom.forEach((item) => {
                    item.style["display"] = type ? "block" : "none";
                  });
                }
              });
              i++;
            } else {
              clearInterval(interval);
            }
          }, 3000);
        }
      },
      addEvent(className, eventType, callback) {
        let dom = this.getElement(className)[0];
        dom.addEventListener(eventType, callback);
      },
      // 添加外部样式
      addCss(className, query) {
        let dom = this.getElement(className)[0];
        Object.keys(query).forEach((item) => {
          dom.style[item] = query[item];
        });
      },
      // 生成多选框
      checkBox(item) {
        let checkObj = {
          tag: "input",
          prop: {
            type: "checkbox",
            id: item.for,
            domId: item.domId,
            index: item.index,
            event: item.getEvent,
            on: {
              change: (e) => {
                var target = e.target,
                  targetTag = target.tagName;
                if (targetTag === "INPUT") {
                  if (GM_listValues().includes(target.id)) {
                    GM_setValue(target.id, target.checked);
                  }
                  if (typeof item.getEvent == "function") {
                    item.getEvent(target.checked);
                  } else {
                    var event = target.getAttribute("event");
                    event != "undefined"
                      ? eval(
                          `${event}(${target.checked}, '${target.attributes.domId.value}')`
                        )
                      : console.log("没设置事件，不需要执行");
                  }
                }
              },
            },
          },
        };

        if (item.checked) {
          checkObj.prop.checked = true;
        }

        let currentDom = {
          tag: "div",
          prop: {
            class: "checkbox-item",
          },
          children: [
            checkObj,
            {
              tag: "label",
              prop: {
                class: "form-check-label",
                for: item.for,
                domId: item.domId,
              },
              children: item.label,
            },
          ],
        };
        return currentDom;
      },

      // 生成按钮
      buttonBox(item) {
        return {
          tag: "button",
          prop: {
            class: item.class? item.class : "tools-button",
            on: {
              click: (e) => {
                var target = e.target,
                  targetTag = target.tagName;
                if (targetTag == "BUTTON") {
                  if (typeof item.getEvent == "function") {
                    item.getEvent(target.value);
                  } else {
                    eval(`${item["getEvent"]}()`);
                  }
                }
              },
            },
          },
          children: item.label,
        };
      },

      // 生成单选
      radioBox(item) {
        let radio = {
          tag: "input",
          prop: {
            type: item.type,
            name: "radio",
            id: item.for,
            on: {
              change: (e) => {
                var target = e.target,
                  targetTag = target.tagName;

                if (targetTag == "INPUT") {
                  if (typeof item.getEvent == "function") {
                    item.getEvent(target.checked);
                  } else {
                    eval(`${item["getEvent"]}()`);
                  }
                }
              },
            },
          },
        };

        if (item.checked) {
          radio.prop.checked = true;
        }

        let radioVdom = {
          tag: "div",
          prop: {
            class: "radio-item",
          },
          children: [
            radio,
            {
              tag: "span",
              prop: {
                class: "radio-label",
              },
              children: item.label,
            },
          ],
        };
        return radioVdom;
      },

      // 生成输入框
      inputBox(item) {
        let input = {
          tag: "input",
          prop: {
            type: "text",
            id: item.for,
            class: "tools-input", 
            domId: item.domId,
            event: item.getEvent,
            on: {
              change: (e) => {
                var target = e.target,
                  targetTag = target.tagName;
                if (targetTag === "INPUT") {
                  if (GM_listValues().includes(target.id)) {
                    GM_setValue(target.id, target.value);
                  }
                  if (typeof item.getEvent == "function") {
                    item.getEvent(target.value);
                  } else {
                    var event = target.getAttribute("event");
                    event != "undefined"
                      ? eval(
                          `${event}(${target.value}, '${target.attributes.domId.value}')`
                        )
                      : console.log("没设置事件，不需要执行");
                  }
                }
              },
            },
          },
        };

        let inpputVdom = {
          tag: "div",
          prop: {
            class: "input-item",
          },
          children: [
            {
              tag: "span",
              prop: {
                class: "input-label",
              },
              children: item.label,
            },
            input
          ],
        };
        return inpputVdom;
      },

      // 创建 DOM 元素的方法
      render(Vnode) {
        let { tag, prop, children } = Vnode;
        let el = document.createElement(tag);
        Object.keys(prop).forEach((item) => {
          el.setAttribute(item, prop[item]);
          if (item === "on") {
            let eventObject = prop[item];
            Object.keys(eventObject).forEach((eventItem) => {
              el.addEventListener(eventItem, (e) => eventObject[eventItem](e));
            });
          }
        });

        if (children instanceof Array) {
          children.forEach((item) => {
            el.appendChild(this.render(item));
          });
        } else {
          el.textContent = children;
        }
        return el;
      },
      // 获取元素
      getElement(className) {
        let domList = document.querySelectorAll(className);
        if (!domList || domList.length === 0) {
          return "";
        } else {
          return domList;
        }
      },

      // 添加主页面
      domHtml(title) {
        let DomHtml = `
              <div class='position'>
                  <svg t="1661751782189" id="tools-ui-main" class="tools-svg icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1727">
                      <path
                          d="M392.2432 477.3376H244.0192c-49.3056 0-89.2928-39.9872-89.2928-89.2928V239.8208c0-49.3056 39.9872-89.2928 89.2928-89.2928h148.224c49.3056 0 89.2928 39.9872 89.2928 89.2928v148.224c0 49.3056-39.9872 89.2928-89.2928 89.2928zM392.2432 868.3008H244.0192c-49.3056 0-89.2928-39.9872-89.2928-89.2928V630.784c0-49.3056 39.9872-89.2928 89.2928-89.2928h148.224c49.3056 0 89.2928 39.9872 89.2928 89.2928v148.224c0 49.3056-39.9872 89.2928-89.2928 89.2928zM785.0496 868.3008h-148.224c-49.3056 0-89.2928-39.9872-89.2928-89.2928V630.784c0-49.3056 39.9872-89.2928 89.2928-89.2928h148.224c49.3056 0 89.2928 39.9872 89.2928 89.2928v148.224c0 49.3056-39.9872 89.2928-89.2928 89.2928zM647.7824 467.0464l-90.0096-90.0096c-34.8672-34.8672-34.8672-91.4432 0-126.3104l90.0096-90.0096c34.8672-34.8672 91.4432-34.8672 126.3104 0l90.0096 90.0096c34.8672 34.8672 34.8672 91.4432 0 126.3104l-90.0096 90.0096c-34.9184 34.8672-91.4432 34.8672-126.3104 0z"
                          fill="#31cdac" p-id="1728">
                      </path>
                  </svg>
                  <div id="tools-main" class="tools-sidebar">
                      <div class="tools-header">
                          <h4>${title}</h4>
                      </div>
                      <div class="tools-body"></div>
                  </div>
              </div>
          `;
        let app = document.createElement("div");
        app.setAttribute("id", "toolsUI");
        app.setAttribute("class", "tools-container");
        document.querySelectorAll("body")[0].appendChild(app);
        app.innerHTML = DomHtml;
      },
      initMainEvent() {
        this.addEvent("#tools-ui-main", "click", (e) => {
          this.addCss("#tools-main", {
            display: "inherit",
          });
        });

        // 设置鼠标移入svg 显示主菜单
        this.addEvent("#tools-ui-main", "mouseenter", (e) => {
          this.addCss("#tools-main", {
            display: "inherit",
          });
        });

        this.addEvent("#tools-main", "mouseleave", () => {
          this.addCss("#tools-main", {
            display: "none",
          });
        });

        var screen_width = document.body.offsetWidth;
        var screen_height = window.innerHeight;

        let father = this.getElement("#toolsUI")[0];

        if (GM_getValue("x")) {
          father.style.top = GM_getValue("y");
          father.style.left = GM_getValue("x");
        }

        this.addEvent("#tools-ui-main", "mousedown", (e) => {
          var x = e.pageX - father.offsetLeft;
          var y = e.pageY - father.offsetTop;

          function move(e) {
            let Py = e.pageY - y;
            let Px = e.pageX - x;
            father.style.top = Py + "px";
            father.style.left = Px + "px";

            if (Py < 20) {
              father.style.top = 20 + "px";
            } else if (Py > screen_height - 50) {
              father.style.top = screen_height - 50 + "px";
            }

            if (Px < 5) {
              father.style.left = 5 + "px";
            } else if (Px > screen_width - 50) {
              father.style.left = screen_width - 50 + "px";
              this.getElement("#tools-ui-main")[0].style.reight = "5px";
            }

            GM_setValue("x", father.style.left);
            GM_setValue("y", father.style.top);
          }
          document.addEventListener("mousemove", move);
          document.addEventListener("mouseup", function () {
            document.removeEventListener("mousemove", move);
          });
        });

        this.addEvent("#tools-ui-main", "touchstart", (e) => {
          var x = e.changedTouches[0].pageX - father.offsetLeft;
          var y = e.changedTouches[0].pageY - father.offsetTop;

          function move(e) {
            let Py = e.changedTouches[0].pageY - y;
            let Px = e.changedTouches[0].pageX - x;
            father.style.top = Py + "px";
            father.style.left = Px + "px";

            if (Py < 20) {
              father.style.top = 20 + "px";
            } else if (Py > screen_height - 50) {
              father.style.top = screen_height - 50 + "px";
            }

            if (Px < 5) {
              father.style.left = 5 + "px";
            } else if (Px > screen_width - 50) {
              father.style.left = screen_width - 50 + "px";
              this.getElement("#tools-ui-main")[0].style.reight = "5px";
            }

            GM_setValue("x", father.style.left);
            GM_setValue("y", father.style.top);
          }

          document.addEventListener("touchmove", move);
          document.addEventListener("touchend", function () {
            document.removeEventListener("touchmove", move);
          });
        });
      },
      // 生成虚拟节点
      addMain(config, title) {
        this.addCssResource(
           "https://gitee.com/itbugs/tampermonkey/raw/master/tools.css"
          );

        this.domHtml(title);

        let bodyDom = this.getElement(".tools-body")[0];

        config.forEach((configItem, index) => {
          let vDom = this.render({
            tag: "div",
            prop: {
              class: "tools-ui-item",
            },
            children: [
              {
                tag: "div",
                prop: {
                  class: "tools-ui-config-title",
                },
                children: configItem.title,
              },
              {
                tag: "div",
                prop: {
                  class: "tools-ui-config-center",
                  parentIndex: index,
                },
                children: this.actionDom(configItem.children),
              },
            ],
          });
          bodyDom.appendChild(vDom);
        });
        this.initMainEvent(); 
      },
      // 在 HTML head 中添加 CSS 资源文件
      addCssResource(url) {
        // 检查 GM_xmlhttpRequest 是否可用
        if (typeof GM_xmlhttpRequest === "undefined") {
          console.error("请确保在元数据中添加 @grant GM_xmlhttpRequest");
          return;
        }
        GM_xmlhttpRequest({
          method: "GET",
          url: url,
          onload: (response) => {
            if (response.status === 200) {
              GM_addStyle(response.responseText);
            } else {
              console.error("加载 CSS 资源失败:", response.statusText);
            }
          },
          onerror: (error) => {
            console.error("请求失败:", error);
          },
        });
      },
    };